package com.laber.interceptors;

import com.laber.properties.JwtProperties;
import com.laber.utils.MyJwtUtil;
import com.laber.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.laber.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

//登录拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断当前拦截到的是Controller的方法还是其他资源，
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        String token = request.getHeader("Authorization");
        //验证token
        try {
            //从redis中获取相同的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);
            if (redisToken == null) {
                System.out.println("redisToken为null");
                //token已经失效
                throw new RuntimeException();
            }
//            Map<String, Object> clamis = JwtUtil.parseToken(token);
            Map<String, Object> clamis = MyJwtUtil.parseToken(jwtProperties.getSecret(), token);
            //把业务数据存储放到ThreadLocal中,tomcat会在每次接口请求时创建一个线程
            //而ThreadLocal中存储的数据是线程安全的
            ThreadLocalUtil.set(clamis);
            //放行
            return true;
        } catch (Exception e) {
            //设置响应状态码
            response.setStatus(401);
            //设置响应字符集和响应内容
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=UTF-8");
            String errorMessage = "未登录";
            response.getWriter().write("{\"error\": \"" + errorMessage + "\"}");

            //不放行
            return false;
        }
    }

    //请求完成后触发的拦截方法
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据防止内存泄漏
        ThreadLocalUtil.remove();
    }
}
